package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-28
 * Time: 15:30
 */
//客户端
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //创建Socket对象，指定服务器的IP地址和端口号
        socket = new Socket(serverIp,serverPort);
    }

    //启动客户端
    public void start() throws IOException {
        System.out.println("客户端启动!");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetWork = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true){
                //1.从控制台读取输入的字符串
                System.out.print("-> ");
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request = scannerConsole.next();
                //2.把请求发送给服务器,这里使用printWriter，因为是为了让发送的请求中添加换行符
                printWriter.println(request);
                printWriter.flush();//通过这个flush，主动刷新缓冲区，确保数据发送出去
                //3.从服务器读取响应
                String response = scannerNetWork.next();
                //4.把响应显示在控制台
                System.out.println(response);
            }
        } catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
